<template>
    <!-- 单个选择、直接上传 -->
    <a-upload
        ref="uploadRef"
        list-type="picture-card"
        :show-file-list="false"
        :file-list="fileList"
        :auto-upload="false"
        @change="handleUpload"
        :accept="accept"
        @click.stop
        :class="[{ 'common-upload': fileList.length }, { 'style': !isInitStyle }]"
    >
        <template #upload-button>
            <slot>
                <i class="add">+</i>
            </slot>
            <div class="mask"></div>
        </template>
    </a-upload>
</template>
<script lang="ts" setup>
const props = defineProps({
    accept: { type: String, default: () => { return '*' } }, // image/*
    isUpload: { type: Boolean, default: () => { return true } }, // 是否上传(true则上传只返回上传成功后的url, false则返回上传后的信息)
    isInitStyle: { type: Boolean, default: () => { return false } }, // 初始化样式
    isBase64: { type: Boolean, default: () => { return false } }, // 上传图片是否返回转base64再返回
	size: { type: String, default: () => { return '' } },
})
import { getFileType, getFileName } from '@/utils/index';
import * as Api from '@/api/common';
const uploadRef = ref(null);
const uploadUrl = ref(null);
const fileList = ref([]); // 文件列表
const emit = defineEmits(['handleUpload']);
const message = useMessage();
// const base64Url = ref(''); // base64地址
const imgInfo = ref({
    width: '',
    height: '',
    base64: '',
}); // 图片信息

// 上传文件
const handleUpload = async (e) => {
    try{
        const file = e.length === 1 ? e[0].file : e[e.length - 1].file;
        if(props.size){
            const size = 1024 * 1024 * props.size;
            if(file.size > size){
                message.error(`文件不能大于${props.size}M`);
                return;
            }
        }
        const fromData = new FormData();
        fromData.append('file', file);
        const isImg = file.type.startsWith('image');
        if(props.isBase64 && isImg){
            await beforeUpload(file);
        }
        if(props.isUpload){
            let https = Api.ApiUpload; // 默认文件上传
            if(isImg){ // 图片上传
                https = Api.ApiUploadMini;
            }
            const res = await https(fromData);
            if(res?.id){
                fileList.value = e || [];
                const { id, ext, size, url, filename, thFilename, originalFilename } = res;
                const isGif = ext === 'gif';
                imgInfo.value.gifPreviewUrl = `${isGif ? filename : thFilename}`;
                const newUrl = isGif ? filename : thFilename;
                emit('handleUpload', {
                    fileId: id,
                    fileName: getFileName(originalFilename),
                    originalFilename,
                    fileSize: size,
                    fileExt: ext,
                    fileType: getFileType(isImg ? newUrl : url),
                    fileUrl: isImg ? newUrl : filename,
                    fileImgInfo: imgInfo.value,
                    fileInitName: filename,
                });
            }
        }else{
            emit('handleUpload', fromData);
        }
    }catch(err){console.log(err);}
}

// 上传前的钩子函数---获取图片信息
const beforeUpload = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            const img = new Image();
            img.src = e.target.result;
            imgInfo.value.base64 = e.target.result;
            img.onload = () => {
                imgInfo.value.width = img.width;
                imgInfo.value.height = img.height;
                // 可以在这里进行其他操作，比如根据宽高进行验证等
                resolve(file);
            };
            // console.log('图片信息====', imgInfo.value);
            img.onerror = () => {
                console.error('图片加载失败');
                reject();
            };
        };
        reader.onerror = () => {
            console.error('文件读取失败');
            reject();
        };
        reader.readAsDataURL(file);
    });
};

defineExpose({
    uploadUrl
})
</script>
<style lang="scss" scoped>
.arco-upload{
    width: 100%;
    display: inline-flex;
    justify-content: center;
    border-radius: 4px;
    position: relative;
    &.common-upload{
        border: none !important;
        background: none !important;
        &:hover{
            border: none;
            .mask{
                opacity: 1 !important;
            }
        }
    }
    &.style{
        width: 80px !important;
        height: 80px;
        border: 1px dashed #ddd;
        background: rgb(242,243,245);
        &:hover{
            background: rgb(229,230,235);
            border: 1px dashed rgb(201,205,212);
            .mask{
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                z-index: 9;
                background: rgba(0,0,0,0.3);
                opacity: 0;
            }
        }
        :deep(span){
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 100% !important;
            height: 100%;
            img{
                width: 100%;
                height: 100%;
            }
        }
    }
    .add{
        font-size: 24px;
        color: #999;
    }

    :deep(span){
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        img{
            width: 100%;
            height: 100%;
        }
    }
    :deep(.arco-upload-picture-card){
        opacity: 0;
    }
}
</style>
